package org.mspring.platform.counter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @since 2014年4月25日
 * @author Gao Youbo
 */
public class SyncThread implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(SyncThread.class);
    private volatile boolean go;
    private final long SLEEP_INTERVAL;
    private Runnable target;
    private String name;
    private boolean daemon;
    private Thread thread;

    public SyncThread(long sleepInterval, Runnable target) {
        this.SLEEP_INTERVAL = sleepInterval;
        this.target = target;
    }

    public void setTarget(Runnable target) {
        this.target = target;
    }

    public void setDaemon(boolean daemon) {
        this.daemon = daemon;
    }

    public void setName(String name) {
        this.name = name;
    }

    public synchronized void start() {
        if (thread == null) {
            go = true;
            if (name != null) {
                thread = new Thread(this, name);
            } else {
                thread = new Thread(this);
            }
            thread.setDaemon(daemon);
            thread.start();
        }
    }

    public synchronized void destroy() {
        if (thread != null) {
            go = false;
            thread.interrupt();
        }
    }

    @Override
    public void run() {
        while (go) {
            try {
                target.run();
            } catch (Exception ex) {
                log.info(ex.getMessage());
            }
            try {
                Thread.sleep(SLEEP_INTERVAL);
            } catch (InterruptedException e) {
                log.warn("同步线程错误", e);
            }
        }
    }
}
